import {
  AppListItem,
  AppListReq,
  AppListRes,
  CreateAppReq,
  UpdateAppReq,
  UploadImageReq,
  FcsUploadImageReq,
  UpdateSurveyReq,
  UpdateBrandingInfo,
  ExtensionInfo,
  ExtensionpageData,
  InitializeData,
  GetReviewAppListReq,
  GetReviewAppListRes,
  ReviewAppReq,
  ReviewAppRes,
  ApprovedRes,
} from '@/common/types';
import apiClient from '../apiClient';
import { AppDetailType, AppListItemType, AppTypeEnum, TeamAppListItemType } from '@/types/app/type';
import { AppBasicInfo, AppUpdateParams, ListAppBody, TeamAppListResponse } from '@/types/app/api';
import {
  defaultNodeVersion,
  FlowNodeTemplateTypeEnum,
  FlowNodeTypeEnum,
} from '@/types/workflow/constant';
import { ParentIdType, ParentTreePathItemType } from '@/types/workflow/node';

export enum AppApi {
  App = '/openapi/v1/app',
  AppDetail = '/chat/share',
  GetAppDetailById = '/api/ruigpt/main/application/detail',
  DelAppById = '/api/ruigpt/main/application/remove',
  PutAppById = '/api/ruigpt/main/application/modify',
  UpdateAppInfo = '/openapi/v2/apps/update/basic_info',
  OutLinkList = '/api/ruigpt/help/outLink/list',
  UploadImage = '/api/ruigpt/shared/document/uploadImage',
  Initialize = '/openapi/v1/initialize',
  SurveyApi = '/openapi/v1/survey',
  ExtensionApi = '/openapi/v1/extension',
  ExtensionCategoriesApi = '/openapi/v1/extension/categories',
  ExtensionSystemsApi = '/openapi/v1/extension/systems',
  ExtensionCategorieFillApi = '/openapi/v1/extension/fillvalue/category',
  ExtensionSystemFillApi = '/openapi/v1/extension/fillvalue/system',
  FcsUploadImage = '/fcs/openapi/v1/file/save',
  ExtensionTemplateDownload = '/openapi/v1/extension/download/template',
  ExtensionBatchCreate = '/openapi/v1/extension/batch/create/excel',
  ExtensionBatchDelete = '/openapi/v1/extension/batch/delete',
  ExtensionBatchCreateStatus = '/openapi/v1/extension/batch/create/status',
  ExtensionBatchCreateTerminate = '/openapi/v1/extension/batch/create/terminate',

  /**
   * 获取APP列表
   */
  GetMyApps = '/api/ruigpt/main/application/list',
  GetAppFolderPath = '/api/ruigpt/main/application/folder/path',

  /**
   * 获取团队应用列表
   */
  GetTeamApps = '/openapi/v2/apps/team/list',

  AppReviewList = '/openapi/v2/apps/review/list',
  AppReviewHistory = '/openapi/v2/apps/review/history',
  AppReview = '/openapi/v2/apps/review',
  Approved = '/openapi/v2/apps/approved/list',
}
/**
 * 获取APP列表
 */
export const getMyApps = (data?: ListAppBody) =>
  apiClient.post<AppListItemType[]>({ url: AppApi.GetMyApps, data });

/**
 * 获取团队应用列表
 */
export const getTeamApps = () => apiClient.get<TeamAppListResponse>({ url: AppApi.GetTeamApps });

export const getTeamAppTemplates = () =>
  getTeamApps().then((res) =>
    res.app_list.map((app) => ({
      tmbId: app.tmbId,
      id: app.id,
      pluginId: app.id,
      isFolder:
        app.type === AppTypeEnum.folder ||
        app.type === AppTypeEnum.httpPlugin ||
        app.type === AppTypeEnum.toolSet,
      templateType: FlowNodeTemplateTypeEnum.teamApp,
      flowNodeType:
        app.type === AppTypeEnum.workflow
          ? FlowNodeTypeEnum.appModule
          : app.type === AppTypeEnum.toolSet
          ? FlowNodeTypeEnum.toolSet
          : FlowNodeTypeEnum.pluginModule,
      avatar: app.avatar,
      name: app.name,
      intro: app.intro,
      showStatus: false,
      version: app.pluginData?.nodeVersion || defaultNodeVersion,
      isTool: true,
    })),
  );

export const getAppFolderPath = (parentId: ParentIdType) => {
  if (!parentId) return Promise.resolve<ParentTreePathItemType[]>([]);
  return apiClient.get<ParentTreePathItemType[]>({
    url: AppApi.GetAppFolderPath,
    params: { parentId },
  });
};

export const getTeamPlugTemplates = (data?: ListAppBody) =>
  getMyApps(data).then((res) =>
    res.map((app) => ({
      tmbId: app.tmbId,
      id: app._id,
      pluginId: app._id,
      isFolder:
        app.type === AppTypeEnum.folder ||
        app.type === AppTypeEnum.httpPlugin ||
        app.type === AppTypeEnum.toolSet,
      templateType: FlowNodeTemplateTypeEnum.teamApp,
      flowNodeType:
        app.type === AppTypeEnum.workflow
          ? FlowNodeTypeEnum.appModule
          : app.type === AppTypeEnum.toolSet
          ? FlowNodeTypeEnum.toolSet
          : FlowNodeTypeEnum.pluginModule,
      type: app.type,
      avatar: app.avatar,
      name: app.name,
      intro: app.intro,
      showStatus: false,
      version: app.pluginData?.nodeVersion || defaultNodeVersion,
      isTool: true,
    })),
  );

/**
 * 获取app应用详情
 * @param data 查询参数
 * @returns app列表
 */
const appDetail = (id: string) => apiClient.get<AppListItem>({ url: AppApi.App + `/${id}` });

/**
 * 通过appId获取app应用详情
 * @param appId appId
 * @returns app详情
 */
const getAppDetailById = (appId: string) =>
  apiClient.get<AppDetailType>({ url: AppApi.GetAppDetailById, params: { appId } });
/**
 * 通过appId删除app应用
 * @param appId appId
 * @returns
 */
const delAppById = (appId: string) =>
  apiClient.delete<AppListItem>({ url: AppApi.DelAppById, params: { appId } });

/**
 * 通过appId更新app应用
 * @param appId appId
 * @param data 更新数据结构
 * @returns
 */
const putAppById = (id: string, data: AppUpdateParams) =>
  apiClient.put<AppListItem>({ url: `${AppApi.PutAppById}?appId=${id}`, data });

/**
 * 通过appId更新app应用信息
 * @param appId appId
 * @param data 更新数据结构
 * @returns
 */
const postUpdateAppInfo = (id: string, data: AppBasicInfo) =>
  apiClient.post({ url: `${AppApi.UpdateAppInfo}/${id}`, data });

/**
 * 获取app列表
 * @param data 查询参数
 * @returns app列表
 */
const appList = (data: AppListReq) => apiClient.get<AppListRes>({ url: AppApi.App, params: data });
/**
 * 创建app
 * @param data 创建app参数
 * @returns
 */
const createApp = (data: CreateAppReq) => apiClient.post<AppListItem>({ url: AppApi.App, data });
/**
 * 更新app
 * @param data 参数
 * @param id app id
 * @returns
 */
const updateApp = (id: string, data: UpdateAppReq) =>
  apiClient.put<AppListItem>({ url: AppApi.App + `/${id}`, data });

/**
 * 删除app
 * @param id app id
 * @returns
 */
const deleteApp = (id: string) => apiClient.delete<AppListItem>({ url: AppApi.App + `/${id}` });

/**
 * 上传图片
 * @param data 图片数据
 * @returns
 */
const postUploadImage = (data: UploadImageReq) =>
  apiClient.post({
    url: AppApi.UploadImage,
    data,
  });

const initialize = () => apiClient.get<InitializeData>({ url: AppApi.Initialize });
const surveyFetch = (id: string) => apiClient.get({ url: AppApi.SurveyApi + `/${id}/latest` });
// const surveySubmit = (id: string, data: UpdateSurveyReq) => apiClient.post({ url: AppApi.SurveyApi + `/${id}`, data });
const surveySubmit = (data: UpdateSurveyReq) => apiClient.post({ url: AppApi.SurveyApi, data });

// 应用管理
const extensionList = (data?: ExtensionpageData) =>
  apiClient.get({ url: AppApi.ExtensionApi, params: data });
const extensionCategoriesList = (data?: ExtensionpageData) =>
  apiClient.get({ url: AppApi.ExtensionCategoriesApi, params: data });
const extensionSystemsList = (data?: ExtensionpageData) =>
  apiClient.get({ url: AppApi.ExtensionSystemsApi, params: data });
const extensionSystemValueList = (data?: ExtensionpageData) =>
  apiClient.get({ url: AppApi.ExtensionSystemFillApi, params: data });
const extensionCategoryValueList = (data?: ExtensionpageData) =>
  apiClient.get({ url: AppApi.ExtensionCategorieFillApi, params: data });

const extensionCreate = (data: ExtensionInfo) => apiClient.post({ url: AppApi.ExtensionApi, data });
const extensionUpdate = (id: string, data: ExtensionInfo) =>
  apiClient.put({ url: AppApi.ExtensionApi + `/${id}`, data });
const extensionDelete = (id: string) => apiClient.delete({ url: AppApi.ExtensionApi + `/${id}` });

const extensionTemplateDownload = () =>
  apiClient.get({ url: AppApi.ExtensionTemplateDownload, responseType: 'blob' });
const extensionBatchCreate = (data: FcsUploadImageReq) =>
  apiClient.post({
    url: AppApi.ExtensionBatchCreate,
    data,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
const extensionBatchDelete = (data: string[]) =>
  apiClient.post({ url: AppApi.ExtensionBatchDelete, data });

// const extensionBatchCreateStatus = (data: string[]) =>
//   apiClient.get({ url: AppApi.ExtensionBatchCreateStatus, data });

const extensionBatchCreateStatus = (appId: string) =>
  apiClient.get({ url: AppApi.ExtensionBatchCreateStatus, params: { app_id: appId } });

const extensionBatchCreateTerminate = (appId: string) =>
  apiClient.post({ url: AppApi.ExtensionBatchCreateTerminate, data: { app_id: appId } });

/**
 * 获取app应用配置信息
 */
const brandingDetail = (id: string, source: string) =>
  apiClient.get<UpdateBrandingInfo>({ url: AppApi.App + `/${id}/branding?source=${source}` });
const updateBranding = (id: string, data: UpdateBrandingInfo) =>
  apiClient.put({ url: AppApi.App + `/${id}/branding`, data });
const postFcsUploadImage = (data: FcsUploadImageReq) =>
  apiClient.post({
    url: AppApi.FcsUploadImage,
    data,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });

/**
 * open V2
 */
const getAppReviewList = (params: GetReviewAppListReq) =>
  apiClient.get<GetReviewAppListRes>({ url: AppApi.AppReviewList, params });

const getAppReviewHistorList = (params: GetReviewAppListReq) =>
  apiClient.get<GetReviewAppListRes>({ url: AppApi.AppReviewHistory, params });

const reviewApp = (appid: string, data: ReviewAppReq) =>
  apiClient.post<ReviewAppRes>({ url: AppApi.AppReview + `/${appid}`, data });

const getApproved = (searchText?: string) =>
  apiClient.get<ApprovedRes>({ url: AppApi.Approved, params: { searchText } });

export default {
  appDetail,
  getAppDetailById,
  delAppById,
  putAppById,
  postUpdateAppInfo,
  appList,
  createApp,
  updateApp,
  deleteApp,
  postUploadImage,
  initialize,
  surveyFetch,
  surveySubmit,
  brandingDetail,
  updateBranding,
  extensionList,
  extensionCategoriesList,
  extensionSystemsList,
  extensionSystemValueList,
  extensionCategoryValueList,
  extensionCreate,
  extensionUpdate,
  extensionDelete,
  extensionTemplateDownload,
  extensionBatchCreate,
  extensionBatchDelete,
  extensionBatchCreateStatus,
  extensionBatchCreateTerminate,
  postFcsUploadImage,
  getMyApps,
  getTeamAppTemplates,
  getTeamPlugTemplates,
  getAppFolderPath,
  getAppReviewList,
  getAppReviewHistorList,
  reviewApp,
  getApproved,
};
